package com.liam.chinesevietnamesecorpus.service.impl;

import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.liam.chinesevietnamesecorpus.common.exception.ServiceException;
import com.liam.chinesevietnamesecorpus.dto.LoginDTO;
import com.liam.chinesevietnamesecorpus.dto.UserDTO;
import com.liam.chinesevietnamesecorpus.dto.UserUpdateDTO;
import com.liam.chinesevietnamesecorpus.entity.User;
import com.liam.chinesevietnamesecorpus.mapper.UserMapper;
import com.liam.chinesevietnamesecorpus.service.EmailService;
import com.liam.chinesevietnamesecorpus.service.UserService;
import com.liam.chinesevietnamesecorpus.utils.JwtUtils;
import com.liam.chinesevietnamesecorpus.vo.LoginVO;
import com.liam.chinesevietnamesecorpus.vo.UserVO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

/**
 * 用户服务实现类
 * 
 * @author Liam
 */
@Slf4j
@Service
public class UserServiceImpl implements UserService {

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private JwtUtils jwtUtils;

    @Autowired
    private EmailService emailService;

    private final BCryptPasswordEncoder passwordEncoder = new BCryptPasswordEncoder();

    @Override
    public LoginVO login(LoginDTO loginDTO) {
        // 根据用户名或邮箱查询用户
        User user = userMapper.selectByUsernameOrEmail(loginDTO.getUsername());
        if (user == null) {
            throw new ServiceException("用户名或密码错误");
        }

        // 验证密码
        if (!passwordEncoder.matches(loginDTO.getPassword(), user.getPassword())) {
            throw new ServiceException("用户名或密码错误");
        }

        // 检查用户状态
        if (!"active".equals(user.getStatus())) {
            throw new ServiceException("账户已被禁用，请联系管理员");
        }

        // 生成JWT token
        String token = jwtUtils.generateToken(user.getId(), user.getUsername(), user.getRole());

        // 转换为VO对象
        UserVO userVO = BeanUtil.copyProperties(user, UserVO.class);

        return new LoginVO(token, userVO);
    }

    @Override
    @Transactional
    public UserVO register(UserDTO userDTO) {
        // 验证邮箱验证码
        if (!emailService.verifyCode(userDTO.getEmail(), userDTO.getVerificationCode(), "register")) {
            throw new ServiceException("邮箱验证码错误或已过期");
        }

        // 检查用户名是否已存在
        if (existsByUsername(userDTO.getUsername())) {
            throw new ServiceException("用户名已存在");
        }

        // 检查邮箱是否已存在
        if (existsByEmail(userDTO.getEmail())) {
            throw new ServiceException("邮箱已存在");
        }

        // 创建用户对象
        User user = BeanUtil.copyProperties(userDTO, User.class);
        
        // 密码加密
        user.setPassword(passwordEncoder.encode(userDTO.getPassword()));

        // 保存用户
        int result = userMapper.insert(user);
        if (result <= 0) {
            throw new ServiceException("注册失败");
        }

        log.info("用户注册成功：{}", user.getUsername());

        // 转换为VO对象
        return BeanUtil.copyProperties(user, UserVO.class);
    }

    @Override
    public UserVO getUserById(Long id) {
        User user = userMapper.selectById(id);
        if (user == null || "deleted".equals(user.getStatus())) {
            throw new ServiceException("用户不存在");
        }
        return BeanUtil.copyProperties(user, UserVO.class);
    }

    @Override
    @Transactional
    public UserVO updateUser(Long id, UserUpdateDTO userUpdateDTO) {
        // 查询用户是否存在
        User existingUser = userMapper.selectById(id);
        if (existingUser == null || "deleted".equals(existingUser.getStatus())) {
            throw new ServiceException("用户不存在");
        }

        // 检查邮箱是否被其他用户使用
        if (StringUtils.hasText(userUpdateDTO.getEmail()) && 
            !userUpdateDTO.getEmail().equals(existingUser.getEmail())) {
            User emailUser = userMapper.selectByEmail(userUpdateDTO.getEmail());
            if (emailUser != null && !emailUser.getId().equals(id)) {
                throw new ServiceException("邮箱已被其他用户使用");
            }
        }

        // 更新用户信息
        User user = new User();
        user.setId(id);
        BeanUtil.copyProperties(userUpdateDTO, user, "password");

        // 如果需要更新密码
        if (StringUtils.hasText(userUpdateDTO.getPassword())) {
            user.setPassword(passwordEncoder.encode(userUpdateDTO.getPassword()));
        }

        int result = userMapper.updateById(user);
        if (result <= 0) {
            throw new ServiceException("更新失败");
        }

        log.info("用户信息更新成功：{}", existingUser.getUsername());

        // 返回更新后的用户信息
        return getUserById(id);
    }

    @Override
    @Transactional
    public void deleteUser(Long id) {
        // 查询用户是否存在
        User user = userMapper.selectById(id);
        if (user == null || "deleted".equals(user.getStatus())) {
            throw new ServiceException("用户不存在");
        }

        // 软删除：更新状态为deleted
        User deleteUser = new User();
        deleteUser.setId(id);
        deleteUser.setStatus("deleted");

        int result = userMapper.updateById(deleteUser);
        if (result <= 0) {
            throw new ServiceException("删除失败");
        }

        log.info("用户删除成功：{}", user.getUsername());
    }

    @Override
    public boolean existsByUsername(String username) {
        User user = userMapper.selectByUsername(username);
        return user != null;
    }

    @Override
    public boolean existsByEmail(String email) {
        User user = userMapper.selectByEmail(email);
        return user != null;
    }
}
